package com.starblink.android.basic.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;

import androidx.appcompat.widget.AppCompatImageView;

/**
 * 选中和未选中两种状态的ImageView
 */
public class CheckableImageView extends AppCompatImageView implements Checkable {
    private boolean mChecked;
    // 增加需要支持的flag
    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

    public CheckableImageView(Context context) {
        this(context,null);
    }

    public CheckableImageView(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public CheckableImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public int[] onCreateDrawableState(final int extraSpace) {
        // 复写 onCreateDrawableState, 并增加给出新的flag位置, 并根据当前状态，merge进相应的flag
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked())
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        return drawableState;
    }

    // 实现 Checkable 方法，使得ImageView可以和CheckBox类似调用
    @Override
    public void toggle() {
        setChecked(!mChecked);
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void setChecked(final boolean checked) {
        if (mChecked == checked)
            return;
        mChecked = checked;
        refreshDrawableState();
    }
}
